//
//  PictureSelectViewController.swift
//  图片浏览器
//
//  Created by Jacky Sun on 16/5/31.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
import SnapKit

let Identifier = "xxsd"
class PictureSelectViewController: UIViewController {
    /// 初始化数据数组
     lazy var pictureArr = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupCollectionView()
    }
    
    private func setupCollectionView(){
        view.addSubview(colltectionView)
        colltectionView.frame = view.bounds
        colltectionView.dataSource = self
        colltectionView.backgroundColor = UIColor.lightGrayColor()
        colltectionView.registerClass(PhotoCell.self, forCellWithReuseIdentifier: Identifier)
    }
    
    //MARK: -m 懒加载collectionview
    private lazy var colltectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoLayout())
    }


class PhotoLayout: UICollectionViewFlowLayout {
    
    override func prepareLayout() {
        // 行间距
        minimumLineSpacing = 10
        // item间距
        minimumInteritemSpacing = 10
        
        let width = (UIScreen.mainScreen().bounds.size.width - 2 * 10 - 2 * 10) / 3
        itemSize = CGSize(width: width, height: width)
        sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        scrollDirection = .Vertical
    }
    
}


extension PictureSelectViewController: UICollectionViewDataSource, PhotoClickDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureArr.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = colltectionView.dequeueReusableCellWithReuseIdentifier(Identifier, forIndexPath: indexPath) as! PhotoCell
        cell.delegate = self
        cell.image = (pictureArr.count == indexPath.item) ? nil : pictureArr[indexPath.item]
        return cell
    }
    
    // 调用代理
    func addNewImageWithCell(cell: PhotoCell) {
        
        if  !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            print("不能打开相册")
            return
        }
        
        // 打开相册控制器
       let imgVC = UIImagePickerController()
        imgVC.delegate = self
        imgVC.allowsEditing = true
        presentViewController(imgVC, animated: true, completion: nil)
    }
    
    func removeSelectedImageWithCell(cell: PhotoCell) {
        let indexPath = colltectionView.indexPathForCell(cell)
        pictureArr.removeAtIndex(indexPath!.item)
        colltectionView.reloadData()
    }
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print(editingInfo)
        let newIMg = image.returnNewImage(UIScreen.mainScreen().bounds.size.width)
        pictureArr.append(newIMg)
        self.colltectionView.reloadData()
        dismissViewControllerAnimated(true) {
        }
//        let  data =  UIImagePNGRepresentation(image)
//        data?.writeToFile("/Users/mabo/Desktop/jack.png", atomically: true)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

@objc
protocol PhotoClickDelegate: NSObjectProtocol {
    // 添加照片
     optional func addNewImageWithCell(cell: PhotoCell)
    
    // 删除照片
    optional func removeSelectedImageWithCell(cell: PhotoCell)
}

class PhotoCell: UICollectionViewCell {
    
    weak var delegate: PhotoClickDelegate?
    
    var image: UIImage?{
        didSet{
            if let img = image{
                addBtn.setImage(img, forState: .Normal)
                removeButton.hidden = false
            }
            else{
                addBtn.setImage(nil, forState: .Normal)

                
                addBtn.setBackgroundImage( UIImage(named: "compose_pic_add"), forState: .Normal)
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
                removeButton.hidden = true
            }
            addBtn.userInteractionEnabled = (image == nil) ? true : false
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(addBtn)
        addBtn.frame = contentView.bounds
        
        contentView.addSubview(removeButton)
        removeButton.snp_makeConstraints { (make) in
            make.width.equalTo(28)
            make.height.equalTo(removeButton.snp_width).multipliedBy(1.0)
            make.top.equalTo(0)
            make.right.equalTo(0)
        }
    }
    
        private lazy var addBtn: UIButton = {
       let btn = UIButton(type: UIButtonType.Custom)
        btn.imageView?.contentMode = .ScaleAspectFill
       btn.setBackgroundImage( UIImage(named: "compose_pic_add"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        btn.addTarget(self, action: #selector(PhotoCell.addNewPhoto), forControlEvents: .TouchUpInside)
        return btn
    }()
    
    private lazy var removeButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(PhotoCell.removeBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
     //   btn.backgroundColor = UIColor.cyanColor()
        return btn
    }()
    
    // 添加照片
    func addNewPhoto(){
        if delegate!.respondsToSelector(#selector(PhotoClickDelegate.addNewImageWithCell(_:))){
            delegate!.addNewImageWithCell!(self)
        }
    }
    
    // 删除照片
    func removeBtnClick(){
        
        if delegate!.respondsToSelector(#selector(PhotoClickDelegate.removeSelectedImageWithCell(_:))){
            delegate!.removeSelectedImageWithCell!(self)
        }
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
